package com.example.bbs.web.servlet; /**
 * @auther: zhangxin
 * @Description:
 */

import com.example.bbs.model.User;
import com.example.bbs.service.UserService;
import com.example.bbs.service.impl.UserServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.example.bbs.utils.MailUtil.sendMail;

@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        req.setCharacterEncoding("UTF-8");

        Map<String, String> params = new HashMap<>();
        //1.创建文件工厂
        FileItemFactory fac = new DiskFileItemFactory();
        //2.创建上传帮助类
        ServletFileUpload upload = new ServletFileUpload(fac);
        //3.解析请求
        try {
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                //判断是否是表单内容
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                    //System.out.println(item.getFieldName()+":"+item.getString());
                    continue;
                }
                //设置文件名
                params.put("icon",item.getName());
                try(InputStream in = item.getInputStream();
                    FileOutputStream out = new FileOutputStream("D:\\java培训\\java\\09\\workspace\\bbs\\src\\main\\webapp\\imgs\\" + item.getName());) {
                    //二进制内容写入到磁盘
                    //写入到文件
                    byte[] buff = new byte[1024];
                    while (true) {
                        int len = in.read(buff);
                        if (len == -1) {
                            break;
                        }
                        out.write(buff, 0, len);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        String userName = params.get("userName");
        System.out.println(userName);
        String userPassword = params.get("userPassword");
        String userRePassword = params.get("userRePassword");
        String icon = "imgs/" + params.get("icon");
        if (userName.isEmpty() || userName.equals("") || userPassword.isEmpty() || userPassword.equals("") || userRePassword.isEmpty() || userRePassword.equals("")) {
            req.setAttribute("fail", "用户名或密码不能为空");
            req.getRequestDispatcher("/reg.jsp").forward(req, resp);
        } else if (!userPassword.equals(userRePassword)) {
            req.setAttribute("fail", "两次密码不同");
            req.getRequestDispatcher("/reg.jsp").forward(req, resp);
        } else {
            User user = new User(userName, userPassword,icon);
            User u = userService.findUserByUser(user);
            //生成一个激活码
            String code = UUID.randomUUID().toString();

            String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://localhost:8080/Mail/ActiveServlet?code="
                    + code + "'>http://localhost:8080/mail/active.action?code=" + code + "</href></h3></body></html>";
            try {
                sendMail("2122877473@qq.com", "账号激活", content);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (u != null) {
                req.setAttribute("fail", "用户已存在!");
                req.getRequestDispatcher("/reg.jsp").forward(req, resp);
                return;
            }
            Boolean bool = userService.doReg(user);
            if (bool) {
                resp.sendRedirect("/login.jsp");
            } else {
                req.setAttribute("fail", "注册失败");
                req.getRequestDispatcher("/reg.jsp").forward(req, resp);
            }
        }
    }

}
